"""
计算现货-期货之间的基差，
步骤1、先提取主力合约的种类比如螺纹钢[01,05,10]
步骤2、计算不同的合约历史行情序列[01序列，05序列，10序列]
步骤3、计算不同合约对应现货的历史行情序列，比如有2个
步骤4、计算现货与期货价差，根据排列组合有[螺纹01-现货1，……]3×2个
步骤5、上传到Mongodb
"""
import os.path
import pandas as pd
from tools.utils import get_ts_code_to_chinese_name
from tools.utils import loc_collection
from tools.utils import first_dir_exists
from tools.utils import load_config
from cal.cal_fut import generate_main_contract_time_series
from cal.cal_fut import drop_dup
import time


def cal_fut_spot_diff(cfg: dict, ts_code_lower: str, mode):
    symbol = ts_code_lower.split("_")[0].upper()
    ts_to_chin = get_ts_code_to_chinese_name(cfg)
    chinese_name = ts_to_chin[ts_code_lower]
    future_dic, _ = generate_main_contract_time_series(cfg, ts_code_lower, mode, only_close=False)
    collection_ = loc_collection('project_config', 'future_spot_price')
    spot_li = list(collection_.find({'ts_code': ts_code_lower}))
    spot_price_ = {va['指标名称']: pd.Series(data=va['v'], index=va['t'], name=va['指标名称']) for va in spot_li}
    future_price_ = {}
    for k, v_temp in future_dic.items():
        f_col = v_temp.columns.to_list()[0]
        df_temp = v_temp.loc[:, ['ts_code', f_col]]
        df_temp.columns = ['ts_code', f"{chinese_name}{k}"]
        future_price_[f"{chinese_name}{k}"] = df_temp
    dic = {}
    name_dic = {}
    for spot_k, spot_se in spot_price_.items():
        for future_k, future_df in future_price_.items():
            spot_name = spot_se.name
            name = f"{spot_name}-{symbol}{future_k}"
            v_se = diff_of_spot_future(spot_se, future_df, name)
            v_se.name = name
            dic[name] = v_se
            name_dic[name] = {'meiosis': f"{symbol}{future_k}", 'minuend': spot_name}
    print(mode)
    return dic, name_dic


def to_str_time(li):
    return [str(pd.to_datetime(str(s)))[:10] for s in li]


def diff_of_spot_future(se_spot, df_future, name):
    se_spot.index = to_str_time(se_spot.index)
    df_future.index = to_str_time(df_future.index)
    se_spot = drop_dup(pd.DataFrame(se_spot)).iloc[:, -1]
    df_future = drop_dup(pd.DataFrame(df_future))
    trade_date = sorted(list(set([t for t in df_future.index.to_list() if t in se_spot.index.to_list()])))

    se_future = df_future.loc[trade_date, df_future.columns.to_list()[-1]]
    se_spot = se_spot[trade_date]
    diff = se_spot - se_future
    df_diff = pd.DataFrame(diff)
    df_diff['ts_code'] = df_future['ts_code']
    ts_code = df_future['ts_code'].to_list()[-1]
    df_diff.columns = [name, ts_code]
    return df_diff


if __name__ == "__main__":
    # 下载所有tjd_category下面的 基差 数据 到it_data
    mode = "基差"
    path = first_dir_exists()
    cfg = load_config()